const { readFileSync } = require('fs');
const path = require('path');
const gulp = require('gulp');
const less = require('less');
const concat = require('gulp-concat');
const through2 = require('through2');
const NpmImportPlugin = require('less-plugin-npm-import');
const autoprefixer = require('autoprefixer');
const postcss = require('gulp-postcss');
const cleanCss = require('gulp-clean-css');

function transformLess(lessFile, config = {}) {
    const { cwd = process.cwd() } = config;
    const resolvedLessFile = path.resolve(cwd, lessFile);
    let data = readFileSync(resolvedLessFile, 'utf-8');
    data = data.replace(/^\uFEFF/, '');
    // Do less compile
    const lessOpts = {
        paths: [path.dirname(resolvedLessFile)],
        filename: resolvedLessFile,
        plugins: [
            new NpmImportPlugin({ prefix: '~' }),
        ],
    };
    return less.render(data, lessOpts)
        .then(r => r.css);
}

function transer(destPath, lessPaths) {
    console.log('Start compile less');
    return gulp.src(lessPaths)
        .pipe(through2.obj(function (file, encoding, next) {
            transformLess(file.path).then((css) => {
                file.contents = Buffer.from(css);
                file.path = file.path.replace(/\.less$/, '.css');
                this.push(file)
                next();
            }).catch((e) => {
                console.error(e);
            });
        }))
        .pipe(postcss([autoprefixer()]))
        .pipe(concat('index.css'))
        .pipe(cleanCss())
        .pipe(gulp.dest(destPath))
        .on('end', () => {
            console.log('Done compile less');
        });
}
module.exports = transer;